package com.example.attendancesystem.Interceptor;

import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@Component
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Cache-Control", "no-cache,no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        HttpSession session = request.getSession();
        Object emp = session.getAttribute("emp");
        Object admin = session.getAttribute("admin");
        String url = request.getRequestURL().toString();
        if (
                !(null == emp && null == admin) ||
                        url.contains("http://localhost/login") ||
                        url.contains("http://localhost/userLogin") ||
                        url.contains("http://localhost/register") ||
                        url.contains("http://localhost/static/js/jquery-3.1.0.js") ||
                        url.contains("http://localhost/static/layui/css/layui.css") ||
                        url.contains("http://localhost/static/layui/layui.js") ||
                        url.contains("http://localhost/imageVerify") ||
                        url.contains("http://localhost/static/images/login.jpg") ||
                        url.contains("http://localhost/static/images/**") ||
                        url.contains("http://localhost/static/layui/css/modules/laydate/default/laydate.css") ||
                        url.contains("http://localhost/static/layui/css/modules/code.css") ||
                        url.contains("http://localhost/static/layui/css/modules/layer/default/layer.css")) {
            return true;
        }
        request.setAttribute("mess", "请登录");
        response.sendRedirect("/login");
        return false;
        /*if ( null == emp && null == admin  ){ //管理员和员工都没有登录
            request.setAttribute("mess","请登录");
            request.getRequestDispatcher("/login").forward(request, response);
            return false;
        }
        return true;*/
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }

}
